﻿using Excel;
using Sirenix.OdinInspector.Editor;
using Sirenix.OdinInspector;
using Sirenix.Utilities;
using Sirenix.Utilities.Editor;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using YFrameWork.RunTime;
using System;

namespace YFrameWork.Editor
{
    public class LangageEditor : OdinEditorWindow
    {
        private static string PrefixYFrameWork;
        private static string PrefixScripteEditor;
        private static string PrefixScripteRuntime;
        private static string xlsxPath;
        public const string PrefsOk = "ReadMultipleLanguage_ok";

        [MenuItem("YGF/读取语言Excel数据")]
        public static void Open()
        {
            PrefixYFrameWork = Application.dataPath + "/Soppurt/YFrameWork";
            PrefixScripteEditor = Application.dataPath + "/Soppurt/YFrameWork/Scripts/Editor/Language/";
            PrefixScripteRuntime = Application.dataPath + "/Soppurt/YFrameWork/Scripts/RunTime/Language/";
            xlsxPath = Application.dataPath + "/Soppurt/YFrameWork/Language/MultiLanguageData.xlsx";
            var window = GetWindow<LangageEditor>();
            window.ReadExcel();
            // Nifty little trick to quickly position the window in the middle of the editor.
            window.position = GUIHelper.GetEditorWindowRect().AlignCenter(1500, 700);
         
        }

        protected override void OnEnable()
        {
            base.OnEnable();
            var window = GetWindow<LangageEditor>();
            window.ShowTextContennt();
        }

        [LabelText("语言")]
        [OnValueChanged("ShowTextContennt"),GUIColor(0.9f,0.8f,0)]
        public LanguageCountryType LanguageTextType; 

        [LabelText("语言列表")]
        [TableList(IsReadOnly =true,MaxScrollViewHeight =80)]
        public TextList[] textLists;


        private void ShowTextContennt()
        {
            foreach (var item in Resources.Load<MultiLanguageData>("Language/MultiLanguageData").languageUnits)
            {
                if (LanguageTextType == item.country)
                {

                    ChengTextList(item.value_allAreas);
                }
                
            }
           
        }

        private void ChengTextList(List<MultiLanguageUnitArea> value_allAreas)
        {
            textLists = new TextList[value_allAreas.Count];
            int i = 0;
            foreach (var item in value_allAreas)
            {
                TextList textList = new TextList();
                textList.type = item.area.ToString();
                textList.Content  = item.value;
                textLists[i] = textList;
                i++;
            }
           
        }








        public void ReadExcel()
        {
            if (!File.Exists(xlsxPath))
            {
                EditorUtility.DisplayDialog("语言读取", "多语言配置文件不存在", "确定");
                return;
            }

            FileStream stream = File.Open(xlsxPath, FileMode.Open, FileAccess.Read, FileShare.Read);
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
            DataSet dataSet = excelReader.AsDataSet();
            excelReader.Dispose();
            if (dataSet == null)
            {
                Debug.LogError("文件为空!");
                return;
            }
            string areaEnumFilePath = PrefixScripteRuntime + "LanguageTextType.cs";
            string countryEnumFilePath = PrefixScripteRuntime+"LanguageCountryType.cs";
            StringBuilder areaString = new StringBuilder("namespace YFrameWork.RunTime\n{\n\tpublic enum LanguageTextType\n\t{");
            StringBuilder countryString = new StringBuilder("namespace YFrameWork.RunTime\n{\n\tpublic enum LanguageCountryType\n\t{");
            string endContent = "\n\t}\n}";
            DataTable dataTable1 = dataSet.Tables[0];
            int rowCount = dataTable1.Rows.Count;
            int columnsCount = dataTable1.Columns.Count;
            EditorUtility.DisplayProgressBar("读取语言种类", "0/" + (rowCount - 1), 0);
            int realNum = 0;
            for (int i = 1; i < rowCount; i++)
            {
                string value = dataTable1.Rows[i][0].ToString();
                if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value))
                    continue;
                realNum++;
                EditorUtility.DisplayProgressBar("读取语言种类", "已经完成" + realNum, 1);
                areaString.Append("\n\t\t" + value + ",");
            }
            EditorUtility.DisplayProgressBar("读取文字位置种类", "0/" + (columnsCount - 1), 0);
            for (int i = 1; i < columnsCount; i++)
            {
                string value = dataTable1.Rows[0][i].ToString();
                if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value))
                    continue;
                realNum++;
                EditorUtility.DisplayProgressBar("读取文字位置种类", "已经完成" + realNum, 1);
                countryString.Append("\n\t\t" + value + ",");
            }
            countryString.Append("\n\t\tLanguageTypeNum");

            areaString.Append(endContent);
            countryString.Append(endContent);
            if (File.Exists(areaEnumFilePath))
                File.Delete(areaEnumFilePath);
            FileStream areaFs = new FileStream(areaEnumFilePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
            byte[] willWriteAreaBytes = Encoding.UTF8.GetBytes(areaString.ToString());
            areaFs.Write(willWriteAreaBytes, 0, willWriteAreaBytes.Length);
            areaFs.Dispose();
            if (File.Exists(countryEnumFilePath))
                File.Delete(countryEnumFilePath);
            FileStream countryFs = new FileStream(countryEnumFilePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
            byte[] willWriteCountryBytes = Encoding.UTF8.GetBytes(countryString.ToString());
            countryFs.Write(willWriteCountryBytes, 0, willWriteCountryBytes.Length);
            countryFs.Dispose();
            AssetDatabase.Refresh();
            if (!EditorApplication.isCompiling)
            {
                OnCompileComplete();
            }
            else
            {
                EditorUtility.ClearProgressBar();
                PlayerPrefs.SetInt(PrefsOk, 0);
            }
            //Debug.Log("已经完成添加多语言的枚举，请在编译完成后重新读取一次表格");
        }
        public static void OnCompileComplete()
        {
            PlayerPrefs.SetInt(PrefsOk, 1);
            MultiLanguageData data = Resources.Load<MultiLanguageData>("Language/MultiLanguageData");
            if (data == null)
            {
                Debug.LogError("资源为空!");
                return;
            }
            data.languageUnits.Clear();
            xlsxPath = PrefixYFrameWork + "/Language/MultiLanguageData.xlsx";
            if (!File.Exists(xlsxPath))
            {
                Debug.LogError("文件不存在");
                EditorUtility.ClearProgressBar();
                return;
            }
            EditorUtility.DisplayProgressBar("读取多语言表格", "0/0", 0);
            FileStream fs = new FileStream(xlsxPath, FileMode.Open, FileAccess.Read);
            IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
            DataSet dataSet = reader.AsDataSet();
            reader.Dispose();
            if (dataSet == null)
            {
                Debug.LogError("文件为空!");
                return;
            }
            DataTable dataTable1 = dataSet.Tables[0];
            int rowCount = dataTable1.Rows.Count;
            int columnsCount = dataTable1.Columns.Count;
            EditorUtility.DisplayProgressBar("读取多语言内容", "0/" + (columnsCount - 1), 0);
            int realNum = 0;
            for (int columnIndex = 1; columnIndex < columnsCount; columnIndex++)
            {
                if (string.IsNullOrEmpty(dataTable1.Rows[0][columnIndex].ToString()))
                    continue;
                realNum++;
                EditorUtility.DisplayProgressBar("读取多语言内容", "已经完成" + realNum, 1);
                LanguageCountryType languageCountry = (LanguageCountryType)System.Enum.Parse(typeof(LanguageCountryType), dataTable1.Rows[0][columnIndex].ToString());
                MultiLanguageUnit languageUnit = new MultiLanguageUnit()
                {
                    country = languageCountry,
                    value_allAreas = new List<MultiLanguageUnitArea>()
                };
                for (int rowIndex = 1; rowIndex < rowCount; rowIndex++)
                {
                    if (string.IsNullOrEmpty(dataTable1.Rows[rowIndex][0].ToString()))
                        continue;
                    LanguageTextType languageArea = (LanguageTextType)System.Enum.Parse(typeof(LanguageTextType), dataTable1.Rows[rowIndex][0].ToString());
                    MultiLanguageUnitArea languageUnitArea = new MultiLanguageUnitArea()
                    {
                        area = languageArea,
                        value = dataTable1.Rows[rowIndex][columnIndex].ToString()
                    };
                    languageUnit.value_allAreas.Add(languageUnitArea);
                }
                data.languageUnits.Add(languageUnit);
            }
            EditorUtility.ClearProgressBar();
            EditorUtility.SetDirty(data);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            EditorUtility.DisplayDialog("完成", "完成多语言读取", "确定");
        }

        public class TextList
        {
            [ReadOnly]
            public string type;
            [ReadOnly]
            public string Content;
        }
    }
    [InitializeOnLoad]
    public class UnityScriptCompiling : AssetPostprocessor
    {
        [UnityEditor.Callbacks.DidReloadScripts]
        public static void AllScriptsReloaded()
        {
            if (PlayerPrefs.GetInt(LangageEditor.PrefsOk, 1) == 0)
            {
                LangageEditor.OnCompileComplete();
            }
        }
    }

   
}